package net.asfun.jvalog.frame;

import static net.asfun.jvalog.common.log.logger;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import net.asfun.jangod.template.TemplateEngine;
import net.asfun.jvalog.mvc.ModelAndView;
import net.asfun.jvalog.vo.Setting;
import net.asfun.jvalog.vo.Site;

public class JsonableView implements ModelAndView{

	private String name;
	private Map<String, Object> model = new HashMap<String, Object>();
	final static TemplateEngine engine = new TemplateEngine();
	final static String root = "admin/";
	
	static {
		reset();
	}
	
	public static void reset() {
		Map<String, Object> common = new HashMap<String, Object>();
		common.put("site", Site.getInstance());
		engine.setEngineBindings(common);
		if ( Setting.WEB_ROOT.endsWith("/") ) {
			engine.getConfiguration().setWorkspace(Setting.WEB_ROOT + root);
		} else {
			engine.getConfiguration().setWorkspace(Setting.WEB_ROOT + "/" + root);
		}
		logger.info("*********************reset jsonableView");
	}
	
	public JsonableView(){};
	
	public JsonableView(String name) {
		this.name = name;
	}
	
	@Override
	public Map<String, Object> getModel() {
		return model;
	}
	
	@Override
	public void setName(String name) {
		this.name = name;
	}
	
	@Override
	public void render(HttpServletRequest request, HttpServletResponse response) throws IOException {
		if ( name.equals("json") ) {
			response.setContentType("application/json; charset=utf-8");
			response.setHeader("Cache-Control","no-store");
			response.setHeader("Pragma","no-cache");
			response.setDateHeader("Expires", 0);
			try {
				JSONObject jo = new JSONObject();
				for( Map.Entry<String, Object> item : model.entrySet() ) {
					jo.put(item.getKey(), item.getValue());
				}
				response.getWriter().write(jo.toString());
			} catch (Exception e) {
				response.getWriter().write("{type:\"error\",message:\"json encoding error\"}");
			}
			return;
		}
		response.getWriter().write(engine.process(name, model));
	}

	@Override
	public void addObject(String key, Object value) {
		model.put(key, value);
	}
}
